/*
 * SHOPTNT 版权所有。
 * 未经许可，您不得使用此文件。
 * 官方地址：www.shoptnt.cn
 */
package cn.shoptnt.consumer.shop.pagedata;

import cn.shoptnt.client.goods.GoodsClient;
import cn.shoptnt.client.system.PageDataClient;
import cn.shoptnt.consumer.core.event.GoodsChangeEvent;
import cn.shoptnt.framework.util.StringUtil;
import cn.shoptnt.model.base.message.GoodsChangeMsg;
import cn.shoptnt.model.pagedata.PageData;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 微页面数据变更消费者
 *
 * @author zh
 * @version v1.0
 * @since v6.4.0 2017年8月29日 下午3:40:14
 */
@Component
public class PageChangeConsumer implements GoodsChangeEvent {

    @Autowired
    private PageDataClient pageDataClient;
    @Autowired
    private GoodsClient goodsClient;

    /**
     * 商品变化，同步微页面
     *
     * @param goodsChangeMsg 商品变化对象
     */
    @Override
    public void goodsChange(GoodsChangeMsg goodsChangeMsg) {

        try {

            Long[] goodsIds = goodsChangeMsg.getGoodsIds();

            if(goodsChangeMsg.getOperationType().equals(GoodsChangeMsg.UPDATE_OPERATION)){
                //查看改变的商品，楼层中是不是有这些商品
                if (goodsIds.length > 0) {
                    List<PageData> pageList = pageDataClient.selectPageByGoods(goodsIds);
                    if (StringUtil.isNotEmpty(pageList)) {
                        //查出来这些商品的信息
                        List<Map<String, Object>> list = goodsClient.getGoods(goodsIds);
                        //将列表转成map
                        Map<Long, Map<String, Object>> map = list.stream().collect(Collectors.toMap(goods -> Long.parseLong(goods.get("goods_id").toString()), goodsDO -> goodsDO));
                        //循环查询出来的楼层
                        pageList.forEach(page -> {
                            String data = page.getPageData();
                            JSONArray dataList = JSONArray.fromObject(data);
                            dataList.forEach(json -> {
                                JSONObject module = (JSONObject) json;
                                JSONObject dataJson = module.getJSONObject("data");
                                //模块名称
                                String name = module.getString("name");
                                //如果是商品模块或者商品滑块
                                if ("goods".equals(name) || "goods-slider".equals(name)) {
                                    //商品模块
                                    //data.goodsList
                                    JSONArray goodsList = dataJson.getJSONArray("goodsList");
                                    this.replaceGoods(map, goodsList);
                                }
                                //如果是魔方，找出魔方中的商品位置
                                if ("magic-cube".equals(name)) {

                                    JSONArray blockList = dataJson.getJSONArray("blockList");
                                    blockList.forEach(block -> {
                                        //商品
                                        JSONArray goodsList = (JSONArray) ((JSONObject) block).get("goodsList");
                                        this.replaceGoods(map, goodsList);
                                        //tab
                                        JSONArray tabList = (JSONArray) ((JSONObject) block).get("tabList");
                                        if (StringUtil.isNotEmpty(tabList)) {
                                            tabList.forEach(tab -> {
                                                JSONArray tabGoodsList = (JSONArray) ((JSONObject) tab).get("goodsList");
                                                this.replaceGoods(map, tabGoodsList);
                                            });
                                        }
                                    });
                                }
                            });

                            page.setPageData(dataList.toString());
                            pageDataClient.edit(page,page.getId());
                        });
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 替换微页面关联的商品
     * @param goodsMap 最新的商品信息map
     * @param goodsList 微页面的商品
     */
    private void replaceGoods(Map<Long, Map<String, Object>> goodsMap, JSONArray goodsList) {

        if (StringUtil.isNotEmpty(goodsList)) {
            goodsList.forEach(g -> {
                Object goodsId = ((JSONObject) g).get("goods_id");
                Map<String, Object> goods = goodsMap.get(Long.parseLong(goodsId.toString()));
                if (goods != null) {
                    //说明楼层中包含该商品，则修改楼层中商品的信息
                    goods.put("goods_id", goods.get("goods_id").toString());
                    ((JSONObject) g).putAll(goods);
                }
            });
        }

    }

}
